<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>考勤记录</span>
        <div class="header-operations">
          <el-date-picker
            v-model="queryParams.yearMonth"
            type="month"
            format="yyyy年MM月"
            value-format="yyyy-MM"
            placeholder="选择月份"
            @change="handleMonthChange"
          />
          <el-input
            v-model="queryParams.employeeNo"
            placeholder="请输入员工工号"
            clearable
            style="width: 200px"
            size="small"
          />
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
          >查询</el-button>
          <el-button
            type="primary"
            icon="el-icon-download"
            size="small"
            @click="handleExport"
          >导出</el-button>
        </div>
      </div>

      <!-- 日历视图 -->
      <div class="calendar">
        <!-- 星期表头 -->
        <div class="week-header">
          <div class="week-day" v-for="day in weekDays" :key="day">{{ day }}</div>
        </div>
        
        <!-- 日历格子 -->
        <div class="calendar-grid">
          <div 
            v-for="(day, index) in calendarDays" 
            :key="index"
            class="day-cell"
            :class="{
              'other-month': !day.currentMonth,
              'today': day.isToday
            }"
          >
            <div class="date-number">{{ day.date }}</div>
            <div class="attendance-info">
              <template v-if="day.attendance">
                <el-tag :type="getStatusType(day.attendance.status)" size="mini">
                  {{ day.attendance.status }}
                </el-tag>
                <div class="time-info" v-if="day.attendance.checkIn">
                  {{ formatTime(day.attendance.checkIn) }}
                  <template v-if="day.attendance.checkOut">
                    - {{ formatTime(day.attendance.checkOut) }}
                  </template>
                </div>
                <div class="remark" v-if="day.attendance.remark">
                  {{ day.attendance.remark }}
                </div>
              </template>
              <template v-else-if="shouldShowAttendance(day.fullDate)">
                <el-tag type="danger" size="mini">异常</el-tag>
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 图例说明 -->
      <div class="legend">
        <div class="legend-item">
          <el-tag type="success" size="mini">正常</el-tag>
        </div>
        <div class="legend-item">
          <el-tag type="warning" size="mini">迟到/早退</el-tag>
        </div>
        <div class="legend-item">
          <el-tag type="info" size="mini">请假</el-tag>
        </div>
        <div class="legend-item">
          <el-tag type="danger" size="mini">异常</el-tag>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'AttendanceRecord',
  
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      attendanceData: [],
      queryParams: {
        yearMonth: this.getCurrentYearMonth(),
        employeeNo: ''
      }
    }
  },

  computed: {
    currentMonth() {
      if (!this.queryParams.yearMonth) return new Date()
      const [year, month] = this.queryParams.yearMonth.split('-')
      return new Date(year, month - 1)
    },

    calendarDays() {
      const year = this.currentMonth.getFullYear()
      const month = this.currentMonth.getMonth()
      
      // 获取当月第一天是星期几
      const firstDay = new Date(year, month, 1)
      const firstDayWeek = firstDay.getDay()
      
      // 获取当月最后一天
      const lastDay = new Date(year, month + 1, 0)
      
      const days = []
      
      // 添加上月的日期
      const prevMonthLastDay = new Date(year, month, 0).getDate()
      for (let i = firstDayWeek - 1; i >= 0; i--) {
        const date = new Date(year, month - 1, prevMonthLastDay - i)
        days.push({
          date: prevMonthLastDay - i,
          fullDate: date,
          currentMonth: false,
          isToday: this.isSameDay(date, new Date()),
          attendance: this.getAttendanceForDate(date)
        })
      }
      
      // 添加当月的日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i)
        days.push({
          date: i,
          fullDate: date,
          currentMonth: true,
          isToday: this.isSameDay(date, new Date()),
          attendance: this.getAttendanceForDate(date)
        })
      }
      
      // 添加下月的日期
      const remainingDays = 42 - days.length // 保持6行
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month + 1, i)
        days.push({
          date: i,
          fullDate: date,
          currentMonth: false,
          isToday: false,
          attendance: this.getAttendanceForDate(date)
        })
      }
      
      return days
    }
  },

  created() {
    this.fetchAttendanceData()
  },

  methods: {
    getCurrentYearMonth() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      return `${year}-${month}`
    },

    handleMonthChange(val) {
      if (!val) {
        this.queryParams.yearMonth = this.getCurrentYearMonth()
        this.queryParams.employeeNo = localStorage.getItem('userId')
      }
      this.fetchAttendanceData() // 选择月份后直接查询数据
    },

    // handleQuery() {
    //   this.fetchAttendanceData()
    // },

    fetchAttendanceData() {
      const userId = localStorage.getItem('userId')
      request({
        url: '/system/record/list',
        method: 'get',
        params: {
          employeeNo: userId,
          yearMonth: this.queryParams.yearMonth
        }
      }).then(res => {
        if (res.code === 200) {
          this.attendanceData = res.data || []
        }
      })
    },

    getStatusType(status) {
      const statusMap = {
        '正常': 'success',
        '迟到': 'warning',
        '早退': 'warning',
        '请假': 'info',
        '异常': 'danger'
      }
      return statusMap[status] || 'danger'
    },

    formatTime(timeStr) {
      if (!timeStr) return ''
      return timeStr.split('T')[1].substring(0, 5)
    },

    isSameDay(date1, date2) {
      return date1.getFullYear() === date2.getFullYear() &&
             date1.getMonth() === date2.getMonth() &&
             date1.getDate() === date2.getDate()
    },

    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    getAttendanceForDate(date) {
      const dateStr = this.formatDate(date)
      return this.attendanceData.find(item => {
        const itemDate = item.date.split('T')[0]
        return itemDate === dateStr
      })
    },

    shouldShowAttendance(date) {
      const today = new Date()
      const isCurrentMonth = date.getMonth() === this.currentMonth.getMonth()
      const isPastDate = date < new Date(today.setHours(0, 0, 0, 0))
      
      return isCurrentMonth && isPastDate
    },

    handleExport() {
      if (!this.queryParams.employeeNo) {
        this.$message.warning('请输入员工工号')
        return
      }

      this.$confirm('是否确认导出所选月份的考勤记录?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在导出数据，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        const exportData = {
          yearMonth: this.queryParams.yearMonth,
          employeeNo: this.queryParams.employeeNo,
          title: `${this.queryParams.yearMonth}考勤记录`,
          sheetName: '考勤记录',
          headers: [
            { label: '员工', prop: 'employeeName' },
            { label: '上班时间', prop: 'checkIn' },
            { label: '下班时间', prop: 'checkOut' },
            { label: '状态', prop: 'status' }
          ]
        }

        return request({
          url: '/system/record/export',
          method: 'get',
          params: exportData,
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          responseType: 'blob'
        }).then(response => {
          if (!response) {
            this.$message.error('导出失败：未获取到数据')
            loading.close()
            return
          }

          const blob = new Blob([response], { 
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const filename = `考勤记录_${this.queryParams.yearMonth}.xlsx`
          
          if (window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, filename)
          } else {
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = filename
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
            window.URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
          }
          loading.close()
          this.$message.success('导出成功')
        }).catch(error => {
          loading.close()
          this.$message.error('导出失败：' + (error.message || '未知错误'))
          console.error('导出错误:', error)
        })
      }).catch(() => {
        this.$message.info('已取消导出')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .header-operations {
    display: flex;
    align-items: center;
    gap: 10px;  /* 控件之间的间距 */
    
    .el-input {
      margin: 0 10px; /* 输入框左右间距 */
    }

    .el-button {
      margin-left: 0; /* 覆盖 element-ui 默认的按钮间距 */
    }
  }
}

.calendar {
  margin-top: 20px;
  
  .week-header {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
    font-weight: bold;
    
    .week-day {
      padding: 10px;
      background-color: #f5f7fa;
      border: 1px solid #ebeef5;
    }
  }
  
  .calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    border-left: 1px solid #ebeef5;
    border-bottom: 1px solid #ebeef5;
    
    .day-cell {
      min-height: 100px;
      padding: 8px;
      border-right: 1px solid #ebeef5;
      border-top: 1px solid #ebeef5;
      
      &.other-month {
        background-color: #fafafa;
        .date-number {
          color: #c0c4cc;
        }
      }
      
      &.today {
        background-color: #f0f9eb;
        .date-number {
          color: #67c23a;
          font-weight: bold;
        }
      }
      
      .date-number {
        font-size: 14px;
        margin-bottom: 8px;
      }
      
      .attendance-info {
        display: flex;
        flex-direction: column;
        gap: 4px;
        min-height: 24px;
        
        .time-info {
          font-size: 12px;
          color: #606266;
        }
        
        .remark {
          font-size: 12px;
          color: #909399;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

.legend {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 16px;
  padding: 8px;
  border-top: 1px solid #ebeef5;
}
</style>